﻿using System;
using NHibernate;
using NUnit.Framework;

namespace NMA.Infrastructure.NHibernate.Tests.Mapping
{
    using NMA.Domain.Model;
    using NMA.Infrastructure.NHibernate.DomainObject;        

    [TestFixture]
    public class CategoryTest : TestBaseClass
    {
        [Test]
        public void Can_add_category_to_database()
        {
            var category = new Category()
            {
                Id = new Guid(),
                Name = "test category",
                CreatedDate = DateTime.Now,    
                UpdatedDate = DateTime.Now,
                CreatedUser = "abc"
            };

            try
            {
                ISession session = SessionFactory.OpenSession();
                Guid id = (Guid)session.Save(category);
                session.Flush();

                session.Evict(category);

                var catDb = session.Get<Category>(id);

                Assert.IsTrue(category.Id == catDb.Id && category.Name == catDb.Name);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                ISession session = SessionFactory.OpenSession();
                session.Delete(category);
                session.Flush();
                session.Evict(category);
            }
        }

        [Test]
        public void Can_update_category_to_database()
        {
            var category = new Category()
            {
                Id = new Guid(),
                Name = "test category",
                CreatedDate = DateTime.Now,
                UpdatedDate = DateTime.Now,
                CreatedUser = "abc"
            };

            try
            {
                ISession session = SessionFactory.OpenSession();
                Guid id = (Guid)session.Save(category);
                session.Flush();

                session.Evict(category);

                var catDb = session.Get<Category>(id);

                catDb.Name = "test update";

                session.Update(catDb);
                session.Flush();

                session.Evict(catDb);

                var updateCatDb = session.Get<Category>(catDb.Id);

                Assert.IsTrue(catDb.Id == updateCatDb.Id && catDb.Name == updateCatDb.Name);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                ISession session = SessionFactory.OpenSession();
                session.Delete(category);
                session.Flush();
                session.Evict(category);
            }

        }
    }
}
